__author__ = 'JackSong'

import sys
import os.path
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
import logging
from tornado.options import options
from tornado.gen import coroutine
from sqlalchemy.orm import sessionmaker
from config import init_config
from urls import handlers
from ioloop import IOloop
from utils.tools import check_python_version_is_2
from utils.data import get_engine
from utils.redis import get_redis_pool
from tornado.queues import Queue

queues = Queue(maxsize = 10)

if sys.version_info.major == 2:
    reload(sys)
    sys.setdefaultencoding('utf-8')
else:
    import tornado.platform.asyncio
    import asyncio

settings = dict(
    template_path = os.path.join(os.path.dirname(__file__),"templates"),
    static_path = os.path.join(os.path.dirname(__file__),"templates/dist/static"),
)


class Application(tornado.web.Application):
    def __init__(self):
        engine = get_engine()
        tornado.web.Application.__init__(self,handlers,**settings)
        self.session = sessionmaker(bind = engine)
        self.queues = queues
        self.redis = get_redis_pool()
        self.access_log = logging.getLogger("tornado.access")
        streamhandler = logging.StreamHandler()
        self.access_log.removeHandler(streamhandler)


@coroutine
def write_file_queues():
    while True:
        item = yield queues.get()
        try:
            item()
        finally:
            queues.task_done()


def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    print('Server Starting port on %s' % (options.port,))
    instance = IOloop.instance(queues).ioloop
    instance.run_sync(write_file_queues)
    instance.start()


def migrate_database():
    from model import Base
    engine = get_engine()
    Base.metadata.create_all(engine)


def create_admin():
    from model import User
    engine = get_engine()
    session=sessionmaker(bind = engine)()
    user = User()
    user.username = "admin"
    user.set_password("admin")
    user.is_superuser = True
    session.add(user)
    session.commit()

if __name__ == "__main__":
    import sys

    init_config()
    if not check_python_version_is_2():
        asyncio.set_event_loop(asyncio.new_event_loop())
    options.parse_config_file("openssh.conf")
    options.parse_command_line()
    command_len = len(sys.argv)
    if command_len == 1:
        main()
    else:
        {"migrate":migrate_database,"create_admin":create_admin}[sys.argv[1]]()
